package com.taomu.app.zongchouhuli.http.api;

import android.util.Log;

import com.taomu.app.zongchouhuli.entity.BaseChangeResponse;
import com.taomu.app.zongchouhuli.entity.BaseErrorResponse;
import com.taomu.app.zongchouhuli.entity.BaseResponse;
import com.taomu.app.zongchouhuli.entity.BaseResponse2;
import com.taomu.app.zongchouhuli.http.contract.RxJavaBaseCallback;
import com.taomu.app.zongchouhuli.http.res.ResArticleEntity;
import com.taomu.app.zongchouhuli.http.res.ResBankEntity;
import com.taomu.app.zongchouhuli.http.res.ResImportNoticeEntity;
import com.taomu.app.zongchouhuli.http.res.ResLunBoEntity;
import com.taomu.app.zongchouhuli.http.res.ResMainProductListEntity;
import com.taomu.app.zongchouhuli.http.res.ResMyBankListEntity;
import com.taomu.app.zongchouhuli.http.res.ResMyBuyProductEntity;
import com.taomu.app.zongchouhuli.http.res.ResNoticeEntity;
import com.taomu.app.zongchouhuli.http.res.ResOrderEntity;
import com.taomu.app.zongchouhuli.http.res.ResOrderInfoEntity;
import com.taomu.app.zongchouhuli.http.res.ResOrderListEntity;
import com.taomu.app.zongchouhuli.http.res.ResProductDetailEntity;
import com.taomu.app.zongchouhuli.http.res.ResProductEntity;
import com.taomu.app.zongchouhuli.http.res.ResProductRebateEntity;
import com.taomu.app.zongchouhuli.http.res.ResRebateDeatailEntity;
import com.taomu.app.zongchouhuli.http.res.ResSelectBankEntity;
import com.taomu.app.zongchouhuli.http.res.ResSpreadEntity;
import com.taomu.app.zongchouhuli.http.res.ResUpdateInfoEntity;
import com.taomu.app.zongchouhuli.http.res.ResUserInfoEntity;
import com.taomu.app.zongchouhuli.utils.ParseUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;

public class Request extends BaseRequest {

    private static Request _instance;

    private Request(){

    }


    public static Request getIntence(){
        if (_instance == null) {                // Single Checked
            synchronized (Request.class) {
                if (_instance == null) {        // Double checked
                    _instance = new Request();
                }
            }
        }
        return _instance;
    }

    //todo:请求api
    public Observable<String> loginPost(String username, String userpwd){
        return getService().post(getToken(),"",null)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        return responseBody.string();
                    }
                });
    }

    public Observable<String> loginGet(String username,String userpwd){
//        params.put("username",username);
//        params.put("password",pwd);
        Map<String,String> params = new HashMap<>();
        params.put("username",username);
        params.put("password",userpwd);
        return getService().get(getToken(),"api/user/userLogin",params).map(new Function<ResponseBody, String>() {
            @Override
            public String apply(ResponseBody responseBody) throws Exception {
                return responseBody.string();
            }
        });
    }

    /**
     * 注册
     * @param phone
     * @param password
     * @param pay_pass
     * @param code
     * @return
     */
    public Observable<String> getRegister(String phone, String password, String pay_pass, String code,String invitecode){
        return getService().getRegister("api/index/register",phone,password,pay_pass,code,invitecode)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 登录
     * @param phone
     * @param password
     * @return
     */
    public Observable<String> login(String phone, String password){
        return getService().getLogin("api/index/login",phone,password)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 修改性别
     * @param token
     * @param sex
     * @return
     */
    public Observable<String> setGender(String token,String sex){
        return getService().setGenderInfo("api/setting/updateUserSex",token,getUid(),sex)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 修改昵称
     * @param token
     * @param nick
     * @return
     */
    public Observable<String> setNickName(String token,String nick){
        return getService().setNickNameInfo("api/setting/updateNickname",token,getUid(),nick)
                .flatMap(new FlatMapNotDataObserver());
    }

    public Observable<String> getUpdateUserImg(String pic){
        return getService().getSettingHeader("api/setting/updateUserImg", getToken(), getUid(), pic)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    public Observable<String> getUserInfo(String token){
        return getService().getUserInfo("api/user/getUserInfo",token,getUid())
                .flatMap(new FlatMapObservable());
    }

    /**
     * 银行卡列表
     * @param token
     * @return
     */
    public Observable<ResMyBankListEntity> getBankList(String token,String ship,String take){
        return getService().getBankListData("api/Bankcard/index/",token,getUid(),ship,take)
                .flatMap(new Function<ResMyBankListEntity, Observable<ResMyBankListEntity>>() {
                    @Override
                    public Observable<ResMyBankListEntity> apply(ResMyBankListEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else {
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 添加银行卡
     * @param token
     * @param card_username 开户人姓名
     * @param card_phone 开户银行
     * @param card_num 卡号
     * @param phone 电话
     * @param code 验证码
     * @return
     */
    public Observable<String> addBank(String token, String card_username,String card_phone,String card_num,String phone,String code){
        return getService().addBankCard("api/bankcard/add",token,getUid(),card_username,card_phone,card_num,phone,code)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 修改银行卡
     * @param token
     * @param id 银行卡id
     * @param card_username 开户人姓名
     * @param card_phone 开户银行
     * @param card_num 卡号
     * @param phone 电话
     * @param code 验证码
     * @return
     */
    public Observable<String> changedBank(String token,String id ,String card_username,String card_phone,String card_num,String phone,String code){
        return getService().changedBankCard("api/bankcard/updateBankCard",token,getUid(),id,card_username,card_phone,card_num,phone,code)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 获取银行卡信息
     * @param token
     * @param id
     * @return
     */
    public Observable<String> getBankInfo(String token,String id){
        return getService().getBankInfo("api/Bankcard/info",token,getUid(),id)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 删除银行卡
     * @param token
     * @param id
     * @return
     */
    public Observable<String> deleteBankInfo(String token,String id){
        return getService().getBankInfo("api/Bankcard/delBankCard",token,getUid(),id)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 设置支付密码
     * @param token
     * @param phone
     * @param code
     * @param pay_pass
     * @return
     */
    public Observable<String> setTradePwd(String token,String phone,String code,String pay_pass,String confirmpwd,String type){
        return getService().setTradePwd("api/setting/modify_password",token,getUid(),phone,code,pay_pass,confirmpwd,type)
                .flatMap(new FlatMapNotDataObserver());

    }

    /**
     * 找回密码
     * @param phone
     * @param code
     * @param password
     * @return
     */
    public Observable<String> getFindPwd(String phone, String code,String password){
        return getService().getFindPassword("api/index/forgetPassword",phone,password,code)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 获取短信验证码
     * @param phone
     * @return
     */
    public Observable<String> getSmsCode(String phone){
        return getService().getSmsCode("api/index/send_msg",phone)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 获取首页产品列表
     * @param tip
     * @return
     */
    public Observable<ResMainProductListEntity> getMainPageDataList(String tip){
        return getService().getMainPageProductList("api/product/productTop",tip)
                .flatMap(new Function<ResMainProductListEntity, Observable<ResMainProductListEntity>>() {
                    @Override
                    public Observable<ResMainProductListEntity> apply(ResMainProductListEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else{
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 获取产品详情
     * @param _id
     * @return
     */
    public Observable<String> getProductDetailInfo(String _id){
        return getService().getProductDetailInfo("api/product/productInfo",_id)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 获取订单id
     * @param token
     * @param productid
     * @param num
     * @param income_type
     * @return
     */
    public Observable<String> getOrderInfo(String token,String productid,String num,String income_type,String distribution_id){
        return getService().getOrderData("api/ProductPay/submitOrder", token,getUid(), productid, num, income_type,distribution_id)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 余额支付
     * @param token
     * @param order_id
     * @param password
     * @param product_id
     * @return
     */
    public Observable<String> getPayOrder(String token,String order_id,String password,String product_id,String distribution_id){
        return getService().payOrderData("api/order/payOrder", token,getUid(), order_id, password, product_id,distribution_id)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 更多，搜索
     * @param product_name
     * @param ship
     * @param take
     * @param order
     * @param desc
     * @return
     */
    public Observable<ResMainProductListEntity> getProductListData(String product_name,String ship,String take,String order,String desc){
        return getService().getProductListData("api/product/productList",product_name,ship,take,order,desc)
                .flatMap(new Function<ResMainProductListEntity, Observable<ResMainProductListEntity>>() {
                    @Override
                    public Observable<ResMainProductListEntity> apply(ResMainProductListEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else{
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 获取订单列表
     * @param token
     * @param status
     * @param ship
     * @param take
     * @return
     */
    public Observable<ResOrderListEntity> getOrderList(String token, String status, String ship, String take){
        return getService().getOrderList("api/order/orderList",token,getUid(),status,ship,take)
                .flatMap(new Function<ResOrderListEntity, Observable<ResOrderListEntity>>() {
                    @Override
                    public Observable<ResOrderListEntity> apply(ResOrderListEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else{
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 取消订单
     * @param token
     * @param order_id
     * @return
     */
    public Observable<String> cancleOrder(String token,String order_id){
        return getService().cancleOrder("api/order/cancelOrder", token,getUid(),order_id)
                .flatMap(new FlatMapNotDataObserver());
    }

    public Observable<String> deleteOrder(String order_id){
        return getService().deleteOrder("api/order/deleteOrder", getToken(), getUid(), order_id)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 确认手机号
     * @param token
     * @param phone
     * @param code
     * @return
     */
    public Observable<String> confirmPhone(String token,String phone,String code){
        return getService().confirmPhone("api/index/checkNowPhone", token,getUid(), phone,code)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 改变手机号
     * @param token
     * @param phone
     * @param code
     * @return
     */
    public Observable<String> changedPhone(String token,String phone,String code){
        return getService().changedPhone("api/setting/updatePhone", token,getUid(), phone,code)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 获取选择充值信息
     * @return
     */
    public Observable<String> getChoiceRechargeInfo(){
        return getService().getChoiceRechargeInfo("api/Recharge/choiceRechargeWay",getToken(),getUid())
                .flatMap(new FlatMapObservable());
    }

    /**
     * 确认充值
     * @return
     */
    public Observable<String> confirmRecharge(String token,String productid,String orderid,String recharge_username,String recharge_num,String recharge_date,String total_fee,String pay_total_fee,String touch_us,String to_username,String to_num){
        return getService().confirmRecharge("api/Recharge/rechargePost",token,getUid(),productid,orderid,recharge_username,recharge_num,recharge_date,total_fee,pay_total_fee,touch_us,to_username,to_num)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 提现
     * @param token
     * @param total_fee
     * @param bank_id
     * @return
     */
    public Observable<String> getCrash(String token,String total_fee,String bank_id){
        return getService().getCrash("api/recharge/putForward", token,getUid(), Integer.valueOf(total_fee), bank_id)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 我的钱包首页
     * @param token
     * @param type
     * @param type
     * @param ship
     * @param take
     * @return
     */
    public Observable<String> getWallet(String token,String type,String ship,String take){
        return getService().getWallet("api/account/myAccount", token,getUid(), type, ship, take)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 本月佣金
     * @param token
     * @return
     */
    public Observable<String> getThisMonthDistributeFee(String token){
        return getService().getThisMonthDistributeFee("api/ProductPay/thisMonthDistributeFee", token,getUid())
                .flatMap(new FlatMapObservable());
    }

    /**
     * 当日收益详情
     * @param token
     * @param id
     * @return
     */
    public Observable<String> getDistributeInfo(String token,String id){
        return getService().getDistributeInfo("api/ProductPay/productDetailInfo", token,getUid(), id)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 我的返利产品
     * @param token
     * @param ship
     * @param take
     * @return
     */
    public Observable<ResSpreadEntity> getMyDistribute(String token, String ship, String take){
        return getService().getMyDistribute("api/ProductPay/myDistribute", token,getUid(), ship, take)
                .flatMap(new Function<ResSpreadEntity, Observable<ResSpreadEntity>>() {
                    @Override
                    public Observable<ResSpreadEntity> apply(ResSpreadEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else {
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 获取用户等级
     * @return
     */
    public Observable<String> getLevenl(){
        return getService().getLevenl("api/user/userLevel", getToken(), getUid())
                .flatMap(new FlatMapObservable());
    }

    /**
     * 获取联系方式
     * @param id
     * @return
     */
    public Observable<String> getContractInfo(String id){
        return getService().getContractInfo("api/setting/getSys", id,getToken(),getUid())
                .flatMap(new FlatMapObservable());
    }

    /**
     * 我购买的产品
     * @param ship
     * @param take
     * @return
     */
    public Observable<ResMyBuyProductEntity> getMyProductList(String ship, String take){
        return getService().getMyProductList2("api/ProductPay/myProduct", getToken(), getUid(), ship, take)
                .flatMap(new Function<ResponseBody, Observable<ResMyBuyProductEntity>>() {
                    @Override
                    public Observable<ResMyBuyProductEntity> apply(ResponseBody responseBody) throws Exception {
                        String json = responseBody.string();
                        JSONObject jsonObject = new JSONObject(json);
                        String data = jsonObject.getString("data");
                        Log.d("data", "sdadsadsadsadad");
                        if("[]".equals(data)){
                            ResMyBuyProductEntity entity = new ResMyBuyProductEntity();
                            return Observable.just(entity);
                        }
                        return Observable.just(ParseUtil.parseObject(json, ResMyBuyProductEntity.class));
                    }
                });
    }

    /**
     * 获取我的产品详情
     * @param product_id
     * @return
     */
    public Observable<String> getProductIncomeDetail(String ship,String take,String product_id){
        return getService().getProductIncomeDetail("api/ProductPay/productUserInfo",getToken(),getUid(),product_id,ship,take)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 充值
     * @param totle_fee
     * @param recharge_type_id
     * @return
     */
    public Observable<String> getSubmitRechargeOrder(String totle_fee,String recharge_type_id){
        return getService().getSubmitRechargeOrder("api/recharge/rechargeOrder", getToken(), getUid(), totle_fee, recharge_type_id)
                .flatMap(new FlatMapObservable());
    }

    /**
     * 公告列表
     * @return
     */
    public Observable<ResNoticeEntity> getNoticeList(){
        return getService().getNoticeList("api/index/getNoticeList")
                .flatMap(new Function<ResNoticeEntity, Observable<ResNoticeEntity>>() {
                    @Override
                    public Observable<ResNoticeEntity> apply(ResNoticeEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else {
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 公告详情
     * @param id
     * @return
     */
    public Observable<String> getNoticeContent(String id){
        return getService().getNoticeContent("api/index/noticeInfo",id)
                .flatMap(new Function<ResponseBody, Observable<String>>() {
                    @Override
                    public Observable<String> apply(ResponseBody responseBody) throws Exception {
                        return Observable.just(responseBody.string());
                    }
                });
    }

    /**
     * 获取文章详情
     * @param id
     * @return
     */
    public Observable<ResArticleEntity> getArticleInfo(String id){
        return getService().getArticleInfo("api/article/info",id,getToken(),getUid())
                .flatMap(new Function<ResArticleEntity, Observable<ResArticleEntity>>() {
                    @Override
                    public Observable<ResArticleEntity> apply(ResArticleEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else {
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 分享
     * @param productId
     * @param userid
     * @return
     */
    public Observable<String> getShareUrl(String productId,String userid){
//        http://39.98.83.102/api/index/shareUrl?productId=1&userid=2
//        http://39.98.83.102/api/index/shareUrl?productId=1&userid=2
        return getService().getShare("api/index/shareUrl", productId,userid)
                .flatMap(new Function<ResponseBody, Observable<String>>() {
                    @Override
                    public Observable<String> apply(ResponseBody responseBody) throws Exception {
                        return Observable.just(responseBody.string());
                    }
                });
    }

    /**
     * 产品卖出
     * @param id
     * @return
     */
    public Observable<String> getSellProduct(String id){
        return getService().getSellProduct("api/ProductPay/applyReturn", getToken(), getUid(), id)
                    .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 获取银行列表
     * @return
     */
    public Observable<ResSelectBankEntity> getSelectBank(){
        return getService().getSelectBank("api/bankcard/bankList",getToken(),getUid())
                .flatMap(new Function<ResSelectBankEntity, Observable<ResSelectBankEntity>>() {
                    @Override
                    public Observable<ResSelectBankEntity> apply(ResSelectBankEntity data) throws Exception {
                        if("200".equals(data.getRet())){
                            return Observable.just(data);
                        }else if("411".equals(data.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else {
                            return Observable.error(new Throwable(data.getMsg()));
                        }
                    }
                });
    }

    /**
     * 更换结算方式
     * @param id
     * @param income_type
     * @return
     */
    public Observable<String> getChangeJiesuan(String id,String income_type){
        return getService().getChangedJiesun("api/ProductPay/updateIncomeType", getToken(), getUid(), id, income_type)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 轮播图片信息
     * @return
     */
    public Observable<ResLunBoEntity> getLunboInfo(){
        return getService().getLunboInfo("api/index/getAdviseList")
                .flatMap(new Function<ResLunBoEntity, Observable<ResLunBoEntity>>() {
                    @Override
                    public Observable<ResLunBoEntity> apply(ResLunBoEntity resLunBoEntity) throws Exception {
                        if("200".equals(resLunBoEntity.getRet())){
                            return Observable.just(resLunBoEntity);
                        }else if("411".equals(resLunBoEntity.getRet())){
                            return Observable.error(new Throwable("411"));
                        }else {
                            return Observable.error(new Throwable(resLunBoEntity.getMsg()));
                        }
                    }
                });
    }

    /**
     * 钱包转入
     * @param totalfee
     * @param type
     * @return
     */
    public Observable<String> getTranferProductAccount(String totalfee,String type){
        return getService().getTranferProductAccount("api/account/tranferProductAccount", getToken(), getUid(), totalfee, type)
                .flatMap(new FlatMapNotDataObserver());
    }

    /**
     * 结算详情
     * @param id
     * @return
     */
    public Observable<ResRebateDeatailEntity> getRebateDetailInfo(String id){
        return getService().getRebateDetailInfo("api/ProductPay/productInfo",getToken(),getUid(),id)
                .flatMap(new Function<ResRebateDeatailEntity, Observable<ResRebateDeatailEntity>>() {
                    @Override
                    public Observable<ResRebateDeatailEntity> apply(ResRebateDeatailEntity responseBody) throws Exception {
                        if ("200".equals(responseBody.getRet())) {
                            return Observable.just(responseBody);
                        }else{
                            return Observable.error(new Throwable(responseBody.getMsg()));
                        }
                    }
                });
    }

    /**
     * 重要公告
     * @return
     */
    public Observable<ResImportNoticeEntity> getImportNoticeInfo(){
        return getService().getImportNoticeInfo("api/index/getImportNotice")
                .flatMap(new Function<ResponseBody, Observable<ResImportNoticeEntity>>() {
                    @Override
                    public Observable<ResImportNoticeEntity> apply(ResponseBody responseBody) throws Exception {
                        String json = responseBody.string();
                        BaseErrorResponse baseErrorResponse = ParseUtil.parseObject(json, BaseErrorResponse.class);
                        if("200".equals(baseErrorResponse.getRet())){
                            ResImportNoticeEntity entity = ParseUtil.parseObject(json, ResImportNoticeEntity.class);
                            return Observable.just(entity);
                        }else if("201".equals(baseErrorResponse.getRet())){
                            ResImportNoticeEntity entity = new ResImportNoticeEntity();
                            return Observable.just(entity);
                        }else{
                            return Observable.error(new Throwable(baseErrorResponse.getMsg()));
                        }
                    }
                });
    }

    public Observable<ResUpdateInfoEntity> getUpdateApp(String versioncode){
        return getService().getUpdateApp("api/index/get_version","1",versioncode)
                .flatMap(new Function<ResUpdateInfoEntity, Observable<ResUpdateInfoEntity>>() {
                    @Override
                    public Observable<ResUpdateInfoEntity> apply(ResUpdateInfoEntity responseBody) throws Exception {
                        if("200".equals(responseBody.getRet())){
                            return Observable.just(responseBody);
                        }else{
                            return Observable.error(new Throwable(responseBody.getMsg()));
                        }
                    }
                });
    }
}
